package com.henry.base.concurrency.forkjoin;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class MultiThread {
    static int threadNum=100;
    static CountDownLatch latch = new CountDownLatch(threadNum);

    static class ComputeThread implements Callable<Integer> {
        private int num;
        private int beg;
        private int end;
        int sum;

        public ComputeThread(int num) {
            this.num = num;
            this.beg=100*num;
            this.end=beg+100;
        }

        @Override
        public Integer call() {
            for (int i = beg; i < end; i++) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sum += i;
            }
            latch.countDown();
            return sum;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService pool = Executors.newFixedThreadPool(threadNum);
        List<Future<Integer>> futures = new ArrayList<>();
        for (int i = 0; i < threadNum; i++) {
            ComputeThread computeThread = new ComputeThread(i);
            Future<Integer> future = pool.submit(computeThread);
            futures.add(future);
//            future.
        }
        latch.await();
        int sum=0;
        for (Future future : futures) {
            sum+=(Integer) future.get();
//            System.out.println(future);
        }
        System.out.println(sum);
        pool.shutdown();

    }

}
